package internal

import (
	"math/rand"
	"time"
	"game-server/conf"
	"game-server/base"
	"game-server/db"
	"game-server/log"
	"game-server/msg"
	"github.com/name5566/leaf/gate"
	"fmt"
	"strconv"
)

const (
	Reward_AddGolden  = iota + 1
	Reward_LessGolden
	Reward_AddScore
	Reward_LessScore
	Reward_addItem
)
const (
	Item_Answer = iota + 1
	Item_coin
	Item_Boom
)

var nameBase = 100
var birdBase = 500

/**
 *
 * 登陆游戏
 * @param args
 * @return
 */
func handleLogin(args []interface{}) {
	// 收到的 Login 消息
	log.Debug("收到登陆请求")
	message := args[0].(*msg.MsgLogin)
	// 消息的发送者
	userConn := args[1].(gate.Agent)

	openID := message.GetOpenId()
	nickName := message.GetNickName()
	iconUrl := message.GetIconUrl()

	// 输出收到的消息的内容
	log.Debug("Login: openID = %v", openID)
	log.Debug("Login: nickName =  %v", nickName)
	log.Debug("Login: iconUrl =  %v", iconUrl)

	// 逻辑判断
	skeleton.AsynCall(db.ChanRPC, "CheckUser", args[0], func(ret interface{}, err error) {
		if err != nil {
			log.Debug("Login: err = ", err)
		} else {
			uInfo := ret.(base.PlayerInfo)
			log.Debug("uInfo is ", uInfo)
			if uInfo.PlayerId > 0 {
				var info base.PlayerInfo
				var roomInfo base.Pk

				userConn.SetUserData(uInfo.PlayerId)

				userId := uInfo.PlayerId
				ok := base.IsExist("user", userId)

				log.Debug("Login: isExit user = ", ok)
				if !ok {
					info = base.PlayerInfo{
						PlayerId:  uInfo.PlayerId,
						NickName:  uInfo.NickName,
						IconUrl:  uInfo.IconUrl,
						OpenId:  uInfo.OpenId,
						Gold:    uInfo.Gold,
						Score:   uInfo.Score,
						BirdID:  uInfo.BirdID,
						BirdNum: uInfo.BirdNum,
						NameNum: uInfo.NameNum,
						AllRank: uInfo.AllRank,
						Online: true,
						UsedItem: uInfo.UsedItem,
						ItemId: uInfo.ItemId,
						PlayTime: time.Now().Unix(),
						RoomNo:  0, ///todo 要干掉的
					}
					log.Debug("Login: init user = ", info)
					base.Put("user", uInfo.PlayerId, info)
					base.Incr("user")
				} else {
					info = base.Get("user", userId).(base.PlayerInfo)
					// 更新操作时间
					info.ItemId = uInfo.ItemId
					info.PlayerId = uInfo.PlayerId
					info.UsedItem = uInfo.UsedItem
					info.NickName = uInfo.NickName
					info.IconUrl = uInfo.IconUrl
					info.BirdNum = uInfo.BirdNum
					info.BirdID = uInfo.BirdID
					info.Gold = uInfo.Gold
					info.Score = uInfo.Score
					info.AllRank = uInfo.AllRank
					info.NameNum = uInfo.NameNum
					info.PlayTime = time.Now().Unix()
					info.Online = true
					info.RoomNo = 0 ///todo 要干掉的

					if info.UsedItem != 0{
						GiveBackItem(info.UsedItem)
						info.UsedItem = 0
					}
					base.Put("user", uInfo.PlayerId, info)
					if info.RoomNo == 0 {
						info.Gold = uInfo.Gold
						info.Score = uInfo.Score
					}
				}

				log.Info("MsgUserInfo: playerID == ", info.PlayerId)
				log.Info("MsgUserInfo: Gold == ", info.Gold)
				log.Info("MsgUserInfo: Score == ", info.Score)
				log.Info("MsgUserInfo: AllRank == ", info.AllRank)
				log.Info("MsgUserInfo: NameNum == ", info.NameNum)
				log.Info("MsgUserInfo: BirdNum == ", info.BirdNum)

				// 关闭就链接
				log.Debug(" base.InitConn", base.InitConn)
				if base.InitConn[userId] != nil {
					// todo 重复登陆干掉之前的
					base.InitConn[userId].Close()
					log.Debug("Login: close conn = ", base.InitConn[userId], userConn)
				}

				// 记录登录用户
				log.Debug("Login: UserList = ", base.UserList)
				bExist := true
				for _, v := range base.UserList {
					if userId == v {
						bExist = false
					}
				}
				log.Debug("Login: bExist = ", bExist, userId)
				if bExist {
					base.UserList = append(base.UserList, userId)
				}
				log.Debug("Login: UserList = ", base.UserList)

				base.InitConn[userId] = userConn

				base.Put("user", userId, info)

				log.Debug("Login: info = ", info)

				// 如果玩家有房間信息,并且房間存在
				if info.RoomNo > 0 && base.IsExist("room", info.RoomNo) {
					roomInfo = base.Get("room", info.RoomNo).(base.Pk)
					log.Info("Login: roomInfo === ", base.Get("room", info.RoomNo))
					log.Info("Login: RoomNo === ", info.RoomNo)

					if roomInfo.RoundId != 0 && len(roomInfo.Players) > 0 {
						// todo 已经开始比赛，并且玩家信息是改玩家（看看是不是要断线重链）
					}

				}
				log.Info("Login: exist == ", base.IsExist("room", info.RoomNo))
				MsgUserInfo := &msg.MsgUserInfo{
					State:    1,
					PlayerId: uInfo.PlayerId,
					Gold:     uInfo.Gold,
					Score:    uInfo.Score,
					BirdId:   uInfo.BirdID,
					AllRank:  uInfo.AllRank,
				}
				log.Info("MsgUserInfo: State == ", MsgUserInfo.State)
				log.Info("MsgUserInfo: PlayerId == ", MsgUserInfo.PlayerId)
				log.Info("MsgUserInfo: Gold == ", MsgUserInfo.Gold)
				log.Info("MsgUserInfo: Score == ", MsgUserInfo.Score)
				log.Info("MsgUserInfo: AllRank == ", MsgUserInfo.AllRank)
				log.Info("MsgUserInfo: BirdId == ", MsgUserInfo.BirdId)

				userConn.WriteMsg(MsgUserInfo)

			} else {
				// 给发送者回应一个 错误 消息
				errMsg := &msg.MsgError{
					ErrNo: 403,
					Desc:  "登录失败,该玩家不存在",
				}
				userConn.WriteMsg(errMsg)
			}
		}
	})
}

func roomNumber() int32 {
	l := len(base.RoomPool)
	if l == 0 {
		base.RoomTotal[0] += 100
		for i := int(base.RoomTotal[0]); i < int(base.RoomTotal[0]+100); i++ {
			roomNo := int32(i)
			base.RoomPool = append(base.RoomPool, roomNo)
		}
		log.Info("ROOM Pool = ", base.RoomTotal[0], base.RoomPool, len(base.RoomPool))
	}

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	rNum := r.Intn(l)
	roomNo := base.RoomPool[rNum]
	base.RoomPool = append(base.RoomPool[:rNum], base.RoomPool[rNum+1:]...)
	log.Info("ROOM Pool = ", rNum, base.RoomPool[rNum])
	return roomNo
}

func newPlayerInfoBase(info base.PlayerInfo) (player base.PlayerInfo) {
	player = base.PlayerInfo{
		PlayerId: info.PlayerId,
		NickName: info.NickName,
		IconUrl:  info.IconUrl,
		Gold:     info.Gold,
		Score:    info.Gold,
		ItemId:   info.ItemId,
		BirdID:   info.BirdID,
		BirdNum:  info.BirdNum,
		NameNum:  info.NameNum,
	}
	return
}

func newPlayerInfoMsg(info *base.PlayerInfo) (tempPlay msg.PlayerInfo) {
	tempPlay = msg.PlayerInfo{
		PlayerId: info.PlayerId,
		NickName: info.NickName,
		Gold:     info.Gold,
		Score:    info.Score,
		ItemId:   info.ItemId,
		BirdId:   info.BirdID,
		BirdNum:  info.BirdNum,
		NameNum:  info.NameNum,
	}
	return
}

/**
 *
 * 创建房间
 * @param args
 * @return
 */
func handleCreate(args []interface{}) {
	// 收到的 create 消息
	log.Debug("handleCreate=========================================")
	message := args[0].(*msg.MsgCreateRoom)
	// 消息的发送者
	userConn := args[1].(gate.Agent)

	userId := message.GetPlayerId()
	IsPas := message.GetIsPas()
	Password := message.GetPassword()
	PlayerNum := message.GetPlayerNum()
	if IsPas == 0 {
		Password = 0
	}

	// 输出收到的消息的内容
	log.Debug("Create: User = %v", userId)
	log.Debug("Create: IsPas = %v", IsPas)
	log.Debug("Create: Password = %v", Password)
	log.Debug("Create: PlayerNum = %v", PlayerNum)
	log.Debug("Create: isExit = ", base.IsExist("user", userId))
	info := base.Get("user", userId).(base.PlayerInfo)
	log.Debug("Create: info = %v", info)

	//if info.RoomNo > 0 {
	//	// todo 不应该在房间中的
	//	//给发送者回应一个 错误 消息
	//	errMsg := &msg.MsgError{
	//		ErrNo: 403,
	//		Desc:  "在房间中",
	//	}
	//	userConn.WriteMsg(errMsg)
	//	log.Debug("Create: master room exist = ", info.RoomNo)
	//} else {
	// 生成房间号
	roomNo := roomNumber()
	// 创建房间,保存玩家链接
	log.Debug("Create: 创建房间 ", roomNo)
	var players []*base.PlayerInfo
	player := newPlayerInfoBase(info)
	players = append(players, &player)

	var BoomTime int64
	log.Debug("players: conf.Server.MaxBoomTime ", conf.Server.MaxBoomTime)
	log.Debug("players: conf.Server.MinBoomTime ", conf.Server.MinBoomTime)
	log.Debug("players: conf.Server.rand.Float64()*float64(conf.Server.MinBoomTime) ", rand.Float64()*float64(conf.Server.MinBoomTime))
	log.Debug("players: float64(conf.Server.MaxBoomTime-conf.Server.MinBoomTime) ", float64(conf.Server.MaxBoomTime-conf.Server.MinBoomTime))

	BoomTime = int64(rand.Float64()*float64(conf.Server.MinBoomTime) + float64(conf.Server.MaxBoomTime-conf.Server.MinBoomTime))
	log.Debug("players: BoomTime ", BoomTime)

	RewardType := 1
	randomNum := int32(rand.Intn(100))
	if randomNum < 80 {
		RewardType = 2
	}

	roomInfo := base.Pk{
		RoomNo:     roomNo,
		Person:     PlayerNum,
		RoundId:    0,
		Round:      0,
		EggOwnerId: 0,
		PassWord:   Password,
		Players:    players,
		Status:     int32(msg.RoomState_IDLE),
		OpenTime:   time.Now().Unix(),
		GetEggTime: 0,
		RewardType: int32(RewardType),
		Value:      100,
		BoomTime:   BoomTime,
		RoomOwner:  userId,
	}

	base.Put("room", roomNo, roomInfo)
	base.Incr("room")
	// 存储房间号
	base.RoomList = append(base.RoomList, roomNo)

	info = base.Get("user", userId).(base.PlayerInfo)
	info.RoomNo = roomNo
	info.Online = true
	info.PlayTime = time.Now().Unix()
	base.Put("user", info.PlayerId, info)

	log.Debug("Create: userId = ", userId)
	log.Debug("Create: info.Nick = ", info.NickName)
	log.Debug("Create: info.ImgUrl = ", info.IconUrl)
	log.Debug("Create: info.Gold = ", info.Gold)
	log.Debug("Create: info.Score = ", info.Score)
	log.Debug("Create: info.ItemId = ", info.ItemId)
	log.Debug("Create: info.roomNo = ", info.RoomNo)
	log.Debug("Create: info.NameNum = ", info.NameNum)
	log.Debug("Create: info.BirdNum = ", info.BirdNum)

	playerInfo := msg.PlayerInfo{
		PlayerId: info.PlayerId,
		NickName: info.NickName,
		IconUrl:  info.IconUrl,
		Gold:     info.Gold,
		Score:    info.Score,
		ItemId:   info.ItemId,
		BirdId:   info.BirdID,
		NameNum:  info.NameNum,
		BirdNum:  info.BirdNum,
	}
	log.Debug("Create: 房间信息 = ", playerInfo)

	var playerInfos []*msg.PlayerInfo
	// 给发送者回应一个 玩家信息 消息
	playerInfos = append(playerInfos, &playerInfo)

	MsgEnterRoomS2C := &msg.MsgEnterRoomS2C{
		RoomId:    roomNo,
		RoomRound: 0,
		WaitTime:  3,
		Players:   playerInfos,
	}
	log.Debug("Create: MsgEnterRoomS2C = ", MsgEnterRoomS2C)
	log.Debug("Create: MsgEnterRoomS2C = ", MsgEnterRoomS2C.RoomId)
	log.Debug("Create: playerInfos = ", MsgEnterRoomS2C.Players)
	userConn.WriteMsg(MsgEnterRoomS2C)
	//todo 通知房间信息变化
	MsgRoomStateS2C := &msg.MsgRoomStateS2C{
		RoomState: int32(msg.RoomState_IDLE),
		Time:      0,
		EggOwner:  0,
	}
	userConn.WriteMsg(MsgRoomStateS2C)
	//}
}

/**
 *
 * 进入房间
 * @param args
 * @return
 */
func handleEnter(args []interface{}) {

	log.Debug("==========================handleEnter")
	// 收到的 进入房间 消息
	message := args[0].(*msg.MsgJoinRoom)
	// 消息的发送者
	userConn := args[1].(gate.Agent)
	userId := message.GetPlayerId()
	roomNo := message.GetRoomId()
	// 输出收到的消息的内容
	log.Debug("Enter: user = %v", userId)
	log.Debug("Enter: roomId =  %v", roomNo)

	info := base.Get("user", userId).(base.PlayerInfo)
	info.Online = true
	base.Put("user", userId, info)

	if roomNo == 0 {
		roomList := base.Get("roomList", 0)
		ListInfo := roomList.([]int32)
		if len(ListInfo) > 0 {
			roomNo = ListInfo[rand.Intn(len(ListInfo))]
		}
		log.Debug("roomNo", roomNo)
	}

	if roomNo == 0 {
		errMsg := &msg.MsgError{
			ErrNo: 403,
			Desc:  "没有可以加入的房间",
		}
		userConn.WriteMsg(errMsg)
	}

	ok := base.IsExist("room", roomNo)

	if ok {
		room := base.Get("room", roomNo).(base.Pk)
		if (len(room.Players) == int(room.Person)) && room.Status != int32(msg.RoomState_IDLE) {
			errMsg := &msg.MsgError{
				ErrNo: 101,
				Desc:  "房间已满！",
			}
			userConn.WriteMsg(errMsg)
			return
		}

		inRoom := false
		for key, val := range room.Players {
			if val == nil {
				continue
			}

			if val.PlayerId <= 0 {
				continue
			}

			// todo 干掉一个玩家
			if val.PlayerId == userId {
				inRoom = true
				log.Debug("key is", key)
			}
		}

		if inRoom == false {
			log.Debug("新玩家 = ", room)
			// 更新玩家信息
			log.Debug("Enter: 房间信息 = ", room)
			playerInfo := newPlayerInfoBase(info)
			room.Players = append(room.Players, &playerInfo)
			base.Put("room", roomNo, room)
		}

		log.Debug("Enter: 房间信息 = ", room.Players)
		log.Debug("Enter: 玩家信息 = ", info)
		info = base.Get("user", userId).(base.PlayerInfo)
		info.RoomNo = roomNo
		info.PlayTime = time.Now().Unix()
		base.Put("user", userId, info)

		log.Debug("Enter: 玩家信息 = ", info)
		var players []*msg.PlayerInfo
		for _, playerInfo := range room.Players {
			log.Debug("room.playerInfo", playerInfo)
			log.Debug("players == nil", players == nil)
			if playerInfo == nil {
				continue
			}

			if playerInfo.PlayerId <= 0 {
				continue
			}
			playerInfoBase := base.Get("user",playerInfo.PlayerId).(base.PlayerInfo)
			tempPlayer := newPlayerInfoMsg(&playerInfoBase)
			players = append(players, &tempPlayer)
		}

		log.Debug("playersi is :", players)

		// 给发送者回应一个 玩家信息 消息
		userInfo := &msg.MsgEnterRoomS2C{
			RoomId:    roomNo,
			RoomRound: room.RoomNo,
			WaitTime:  3,
			Players:   players,
		}

		MsgRoomStateS2C := &msg.MsgRoomStateS2C{
			RoomState: int32(msg.RoomState_IDLE),
			Time:      5,
			EggOwner:  0,
		}

		/////////////////////////////////////////////
		// todo 推送解除托管
		MsgRobotS2C := &msg.MsgRobotS2C{
			PlayerId: userId,
			IsRobot:  0,
		}
		for _, roomPlayerInfo := range room.Players {
			if roomPlayerInfo == nil {
				continue
			}
			if roomPlayerInfo.PlayerId <= 0 {
				continue
			}
			if nil != base.InitConn[roomPlayerInfo.PlayerId] {
				base.InitConn[roomPlayerInfo.PlayerId].WriteMsg(MsgRobotS2C)
			}
		}
		/////////////////////////////////////////////

		// 给房间所有玩家发
		for _, v := range room.Players {
			if v == nil {
				continue
			}
			if v.PlayerId <= 0 {
				continue
			}
			log.Debug("v.playerID", v.PlayerId)
			log.Debug("base.InitConn[v.PlayerId]", base.InitConn[v.PlayerId])
			if base.InitConn[v.PlayerId] != nil {
				pushInfo := base.Get("user", v.PlayerId).(base.PlayerInfo)
				if pushInfo.RoomNo != room.RoomNo {
					continue
				}
				log.Debug(v.PlayerId, "--------------推送1-------------userInfo", userInfo)
				log.Debug(v.PlayerId, "--------------推送2-------------MsgRoomStateS2C", MsgRoomStateS2C)
				base.InitConn[v.PlayerId].WriteMsg(userInfo)
				base.InitConn[v.PlayerId].WriteMsg(MsgRoomStateS2C)
			}
			//}
		}

	} else {
		// 给发送者回应一个 错误 消息
		errMsg := &msg.MsgError{
			ErrNo: 102,
			Desc:  "房间号有误,请重新输入",
		}
		userConn.WriteMsg(errMsg)
	}
}

/**
 *
 * 退出房间
 * @param args
 * @return
 */
func handleExitRoom(args []interface{}) {
	// 收到的 退出房间 消息
	message := args[0].(*msg.MsgExitRoom)
	// 消息的发送者
	userConn := args[1].(gate.Agent)

	userId := message.GetPlayerId()
	roomId := message.GetRoomId()
	// 输出收到的消息的内容
	log.Debug("Exit: userId = %v", userId)
	log.Debug("Exit: roomId = %v", roomId)

	info := base.Get("user", userId).(base.PlayerInfo)
	room := base.Get("room", info.RoomNo).(base.Pk)
	log.Debug("Exit: room = %v", room, info, base.InitConn)
	roomNo := roomId
	info.RoomNo = 0 // 房间号置空
	if info.UsedItem != 0{
		GiveBackItem(info.UsedItem)
		info.UsedItem = 0
	}
	base.Put("user", userId, info)
	log.Debug("Exit: msg.RoomState(room.Status) = ", msg.RoomState(room.Status))


	switch msg.RoomState(room.Status) {
	case msg.RoomState_START, msg.RoomState_END:
		exitInfo := &msg.MsgExitRoomS2C{
			ExitSuccess: 1,
		}
		userConn.WriteMsg(exitInfo)
		changeEgg := false
		for key, val := range room.Players {
			if val == nil {
				continue
			}
			if val.PlayerId <= 0 {
				continue
			}

			if room.EggOwnerId == userId {
				changeEgg = true
			}
			// todo 干掉一个玩家
			if val.PlayerId == userId {
				log.Debug("干掉一个玩家 玩家id为-1", userId)
				room.Players[key].PlayerId = -1
				base.Put("room", roomNo, room)
				break
			}
		}

		var players []*msg.PlayerInfo
		var playersID []int32
		for _, playerInfo := range room.Players {
			if playerInfo == nil {
				continue
			}
			playerInfoBase := base.Get("user",playerInfo.PlayerId).(base.PlayerInfo)
			tempPlayer := newPlayerInfoMsg(&playerInfoBase)
			players = append(players, &tempPlayer)
			playersID = append(playersID, playerInfo.PlayerId)
		}

		if changeEgg {
			// todo 传蛋
			log.Debug("players is ：========,", playersID)
			ChangeEggOwner(playersID, &room, userId, false)

			//todo 通知玩家信息
			MsgEnterRoomS2C := &msg.MsgEnterRoomS2C{
				RoomId:    room.RoomNo,
				RoomRound: room.RoundId,
				WaitTime:  3,
				Players:   players,
			}
			for _, v := range room.Players {
				if v == nil {
					continue
				}
				if nil != base.InitConn[v.PlayerId] {
					if v.PlayerId != userId {
						log.Info("Exit: 通知房间人数变化 = ", v.PlayerId, room.RoomNo, MsgEnterRoomS2C)
						base.InitConn[v.PlayerId].WriteMsg(MsgEnterRoomS2C)
					}
				}
			}
			room.ExitNo += 1
			log.Debug("Exit: 房间玩家 = ", room.Players)
			log.Debug("Exit: players = ", players)
			log.Debug("Exit: room player exit = ", userId)
		}

	default:
		// todo 什么都不考虑，直接退出房间
		// 给发送者回应一个 玩家信息 消息
		log.Debug("Exit: 玩家信息 = ", info)
		// 修改玩家信息
		base.Put("user", userId, info)
		log.Debug("Exit: 玩家信息 = ", info)
		var status int32
		status = 0
		for key, val := range room.Players {
			if val == nil {
				continue
			}
			// todo 干掉一个玩家
			if val.PlayerId == userId {
				kk := key + 1
				room.Players = append(room.Players[:key], room.Players[kk:]...)
				status = 1
				break
			}
		}
		exitInfo := &msg.MsgExitRoomS2C{			ExitSuccess: status,
		}
		userConn.WriteMsg(exitInfo)
		log.Debug(" 找到退出的玩家状态：", status)
		if status == 1 {
			var players []*msg.PlayerInfo
			for _, playerInfo := range room.Players {
				if playerInfo == nil {
					continue
				}
				if playerInfo.PlayerId <= 0 {
					continue
				}
				playerInfoBase := base.Get("user",playerInfo.PlayerId).(base.PlayerInfo)
				tempPlayer := newPlayerInfoMsg(&playerInfoBase)
				players = append(players, &tempPlayer)
			}

			// 给发送者回应一个 玩家信息 消息
			userInfo := &msg.MsgEnterRoomS2C{
				RoomId:    roomNo,
				RoomRound: room.RoomNo,
				WaitTime:  3,
				Players:   players,
			}

			for _, v := range room.Players {
				if v == nil {
					continue
				}
				if v.PlayerId <= 0 {
					continue
				}
				if base.InitConn[v.PlayerId] != nil {
					log.Info("Exit: 玩家链接 = ", v.PlayerId, base.InitConn[v.PlayerId])
					base.InitConn[v.PlayerId].WriteMsg(userInfo)
				}
			}
			room.ExitNo += 1
			base.Put("room", roomNo, room)
			log.Debug("Exit: 房间玩家 = ", room)
			log.Debug("Exit: room player exit = ", userId)
			log.Debug("Exit: room vote exit = ", userId)
		} else {
			// 退出失败
			exitInfo := &msg.MsgExitRoomS2C{
				ExitSuccess: 0,
			}
			userConn.WriteMsg(exitInfo)
		}
	}


	base.Put("user", info.PlayerId, info)
	base.Put("room", room.RoomNo, room)

}

/**
 *
 * 修改状态（传蛋）
 * @param args
 * @return
 */
func handleChangeEgg(args []interface{}) {
	// 收到的 修改状态 消息
	message := args[0].(*msg.MsgChangeEgg)
	// 消息的发送者
	userConn := args[1].(gate.Agent)

	roomId := message.GetRoomId()
	userId := message.GetPlayerId()
	targerId := message.GetTargerId()
	// 输出收到的消息的内容
	log.Debug("Change: user = %v", userId)
	// 更新玩家状态
	info := base.Get("user", userId).(base.PlayerInfo)
	roomNo := info.RoomNo
	if roomId != info.RoomNo {
		errMsg := &msg.MsgError{
			ErrNo: 403,
			Desc:  "房间号错误",
		}
		userConn.WriteMsg(errMsg)
		return
	}
	room := base.Get("room", roomNo).(base.Pk)

	if room.EggOwnerId != userId {
		errMsg := &msg.MsgError{
			ErrNo: 403,
			Desc:  "您不是彩蛋拥有者",
		}
		userConn.WriteMsg(errMsg)
		return
	}
	room.EggOwnerId = targerId
	room.GetEggTime = time.Now().Unix() //獲得蛋的时间
	base.Put("room", room.RoomNo, room)

	userInfo := &msg.MsgChangeEggS2C{
		RoomId:   info.RoomNo,
		PlayerId: userId,
		TargerId: targerId,
	}

	for _, roomPlayerInfo := range room.Players {
		if roomPlayerInfo == nil {
			continue
		}
		if roomPlayerInfo.PlayerId <= 0 {
			continue
		}
		if nil != base.InitConn[roomPlayerInfo.PlayerId] {
			base.InitConn[roomPlayerInfo.PlayerId].WriteMsg(userInfo)
		}

	}
}

/**
 *
 * 取消托管
 * @param args
 * @return
 */
func handleCancleRobot(args []interface{}) {
	// 收到的 修改状态 消息
	message := args[0].(*msg.MsgCancleRobot)
	// 消息的发送者
	//userConn := args[1].(gate.Agent)
	//roomId := message.GetRoomId()
	userId := message.GetPlayerId()
	// 输出收到的消息的内容
	log.Debug("Change: user = %v", userId)
	// 更新玩家状态
	info := base.Get("user", userId).(base.PlayerInfo)
	roomNo := info.RoomNo

	room := base.Get("room", roomNo).(base.Pk)
	room.GetEggTime = time.Now().Unix()
	base.Put("room", roomNo, room)

	info.Online = true
	base.Put("user", userId, info)

	MsgRobotS2C := &msg.MsgRobotS2C{
		PlayerId: userId,
		IsRobot:  0,
	}
	for _, roomPlayerInfo := range room.Players {
		if roomPlayerInfo == nil {
			continue
		}
		if roomPlayerInfo.PlayerId <= 0 {
			continue
		}
		if nil != base.InitConn[roomPlayerInfo.PlayerId] {
			base.InitConn[roomPlayerInfo.PlayerId].WriteMsg(MsgRobotS2C)
		}
	}
}

/**
 *
 * 使用道具
 * @param args
 * @return
 */
func handleUseItem(args []interface{}) {
	message := args[0].(*msg.MsgUseItem)
	userConn := args[1].(gate.Agent)
	userId := message.GetPlayerId()
	roomId := message.GetRoomId()
	itemId := message.GetItemId()
	targerID := message.GetTargetID()
	value1 := message.GetValue1()
	value2 := message.GetValue2()

	// 输出收到的消息的内容
	log.Debug("Change: user = %v", userId)

	// 更新玩家状态
	info := base.Get("user", userId).(base.PlayerInfo)
	roomNo := info.RoomNo
	if info.RoomNo != roomId{
		log.Error("房间不对=======================",roomNo,roomId)
		return
	}

	room := base.Get("room", roomId).(base.Pk)
	base.Put("user", userId, info)

	hasItem := false
	for key, UserItemId := range info.ItemId {
		if UserItemId == itemId {
			// todo 删除道具
			info.ItemId = append(info.ItemId[:key],info.ItemId[key+1:]...)
			hasItem = true
			break
		}
	}
	base.Put("user",userId,info)

	if hasItem == false {
		log.Error("没有道具")
		errMsg := &msg.MsgError{
			ErrNo: 403,
			Desc:  "没有道具",
		}
		userConn.WriteMsg(errMsg)
		return
	}

	TargetPlayer := base.Get("user", targerID).(base.PlayerInfo)
	if TargetPlayer.UsedItem > 0{
		log.Error("目标已经拥有道具")
		errMsg := &msg.MsgError{
			ErrNo: 404,
			Desc:  "目标已经拥有道具",
		}
		userConn.WriteMsg(errMsg)
		return
	}
	switch itemId {
	//case Item_Boom:
	//		MsgEggBoomS2C := &msg.MsgEggBoomS2C{
	//			RoomId:     roomId,
	//			BoomId:     room.EggOwnerId,
	//			RewardType: room.RewardType,
	//			Value:      room.Value,
	//		}
	//		MsgRoomStateS2C := &msg.MsgRoomStateS2C{
	//			RoomState: int32(msg.RoomState_END),
	//			Time:      5,
	//			EggOwner:  0,
	//		}
	//		room.Value = int32(msg.RoomState_END)
	//		room.EggOwnerId = 0
	//		base.Put("room", room.RoomNo, room)
	//		for _, roomPlayerInfo := range room.Players {
	//			if roomPlayerInfo == nil {
	//				continue
	//			}
	//
	//			if roomPlayerInfo.PlayerId <= 0 {
	//				continue
	//			}
	//
	//			playInfo := base.Get("user", roomPlayerInfo.PlayerId).(base.UserInfo)
	//			if playInfo.UserId == room.EggOwnerId {
	//				switch room.RewardType {
	//				case 1: //奖励金币
	//					playInfo.Gold += room.Value
	//				case 2: //扣除金币
	//					playInfo.Gold -= room.Value
	//				case 3: //奖励积分
	//					playInfo.Score += room.Value
	//				case 4: //扣除积分
	//					playInfo.Score -= room.Value
	//				case 5: //奖励道具
	//					playInfo.ItemId = append(playInfo.ItemId, room.Value)
	//
	//				}
	//			} else {
	//				//其他玩家增加金币
	//				playInfo.Gold += 100
	//			}
	//
	//			if nil != base.InitConn[roomPlayerInfo.PlayerId] {
	//				base.InitConn[roomPlayerInfo.PlayerId].WriteMsg(MsgEggBoomS2C)
	//				base.InitConn[roomPlayerInfo.PlayerId].WriteMsg(MsgRoomStateS2C)
	//			}
	//		}
	default:
		///  答题和金币
		log.Debug("开始答题或者金币")
		targerString := strconv.Itoa(int(targerID))
		itemIdString := strconv.Itoa(int(itemId))
		userIdString := strconv.Itoa(int(userId))
		itemkeyString := targerString + itemIdString + userIdString

		itemkey,_ := strconv.Atoi(itemkeyString)
		log.Debug("生成道具id",itemkey)
		TargetPlayer := base.Get("user", targerID).(base.PlayerInfo)
		TargetPlayer.UsedItem = int32(itemkey) //身上有道具
		base.Put("user", targerID, TargetPlayer)


		item := base.ItemInfo{
			UserID:   userId,
			TargetID: targerID,
			ItemID:   itemId,
			Status:   0,
		}

		log.Debug("物品id",itemkey)
		base.Put("item", int32(itemkey), item)

	}

	MsgUseItemS2C := &msg.MsgUseItemS2C{
		RoomId:   roomId,
		PlayerId: userId,
		TargetID: targerID,
		ItemId:   itemId,
		Value1:   value1,
		Value2:   value2,
	}
	for _, roomPlayerInfo := range room.Players {
		if roomPlayerInfo == nil {
			continue
		}

		if roomPlayerInfo.PlayerId <= 0 {
			continue
		}
		if nil != base.InitConn[roomPlayerInfo.PlayerId] {
			log.Debug("通知玩家使用道具 [%d], [%v]", roomPlayerInfo.PlayerId, MsgUseItemS2C)
			base.InitConn[roomPlayerInfo.PlayerId].WriteMsg(MsgUseItemS2C)
		}
	}
}

/**
 *
 * 开始游戏
 * @param args
 * @return
 */
func handleRoomStart(args []interface{}) {
	message := args[0].(*msg.MsgRoomStart)
	log.Debug("=============handleRoomStart")
	userConn := args[1].(gate.Agent)
	roomId := message.GetRoomId()
	playerId := message.GetPlayerId()
	log.Debug("=============handleRoomStart", roomId)
	roomInfoIn := base.Get("room", roomId)
	if roomInfoIn == nil {
		errMsg := &msg.MsgError{
			ErrNo: 411,
			Desc:  "房间不存在",
		}
		log.Debug("=============房间不存在", roomId)
		userConn.WriteMsg(errMsg)
		return
	}
	roomInfo := roomInfoIn.(base.Pk)
	log.Debug("=============handleRoomStart", roomInfo)
	if roomInfo.Status != int32(msg.RoomState_IDLE) {
		errMsg := &msg.MsgError{
			ErrNo: 411,
			Desc:  "游戏已经开始",
		}
		log.Debug("=============游戏已经开始")
		userConn.WriteMsg(errMsg)
		return
	}
	if roomInfo.RoomOwner != playerId {
		errMsg := &msg.MsgError{
			ErrNo: 410,
			Desc:  "不是房主不可开始游戏",
		}
		log.Debug("=============不是房主不可开始游戏")
		userConn.WriteMsg(errMsg)
		return
	}

	if len(roomInfo.Players) <= 1 {
		errMsg := &msg.MsgError{
			ErrNo: 412,
			Desc:  "人数不足，无法开始游戏",
		}
		log.Debug("=============人数不足，无法开始游戏")
		userConn.WriteMsg(errMsg)
		return
	}

	random := rand.Intn(int(len(roomInfo.Players)))
	//todo 通知房间信息变化
	MsgRoomStateS2C := &msg.MsgRoomStateS2C{
		RoomState: int32(msg.RoomState_START),
		Time:      5,
		EggOwner:  roomInfo.Players[random].PlayerId,
	}
	// todo 开始传蛋
	RewardType := 1
	randomNum := int32(rand.Intn(100))
	if randomNum < 80 {
		RewardType = 2
	}

	roomInfo.Status = int32(msg.RoomState_START)
	roomInfo.EggOwnerId = roomInfo.Players[random].PlayerId //随机给一个人
	roomInfo.StartGameTime = time.Now().Unix()              // 游戏开始时间
	roomInfo.GetEggTime = time.Now().Unix()                 // 传蛋的时间
	roomInfo.OpTime = time.Now().Unix()                     // 传蛋的时间
	roomInfo.RewardType = int32(RewardType)                 //奖励类型
	randValue := 100
	if roomInfo.RewardType == Reward_addItem {
		randValue = 2
	}
	roomInfo.Value = int32(rand.Intn(randValue)) + 1 //奖励value
	base.Put("room", roomId, roomInfo)
	//MsgRoomStateS2C.RoomState = int32(msg.RoomState_START)

	// 给房间所有玩家发
	for _, v := range roomInfo.Players {
		if v == nil {
			continue
		}

		if v.PlayerId <= 0 {
			continue
		}

		log.Debug("handleRoomStart v.playerID", v.PlayerId)
		log.Debug("handleRoomStart base.InitConn[v.PlayerId]", base.InitConn[v.PlayerId])

		if base.InitConn[v.PlayerId] != nil {
			pushInfo := base.Get("user", v.PlayerId).(base.PlayerInfo)

			log.Debug("handleRoomStart v.pushInfo", pushInfo.RoomNo)
			log.Debug("handleRoomStart v.roomInfo", roomInfo.RoomNo)

			if pushInfo.RoomNo != roomInfo.RoomNo {
				continue
			}
			log.Debug(v.PlayerId, "--------------开始游戏推送-------------MsgRoomStateS2C", MsgRoomStateS2C)
			base.InitConn[v.PlayerId].WriteMsg(MsgRoomStateS2C)
		}
	}
}

/**
 *
 * 修改鸟外形
 * @param args
 * @return
 */
func handleChangeBird(args []interface{}) {
	message := args[0].(*msg.MsgChangeBird)
	userConn := args[1].(gate.Agent)
	playerId := message.GetPlayerId()
	birdId := message.GetBirdId()
	playerInfo := base.Get("user", playerId).(base.PlayerInfo)
	goldenNeed := playerInfo.BirdNum * int32(nameBase)
	if playerInfo.Gold < goldenNeed {
		errMsg := &msg.MsgError{
			ErrNo: 402,
			Desc:  "金币不足",
		}
		userConn.WriteMsg(errMsg)
		return
	}
	playerInfo.BirdNum = playerInfo.BirdNum + 1
	playerInfo.BirdID = birdId
	playerInfo.Gold = playerInfo.Gold - goldenNeed
	base.Put("user", playerId, playerInfo)
	skeleton.AsynCall(db.ChanRPC, "UpdateBird", args[0], func(ret interface{}, err error) {
		log.Debug("===============ret", ret)
	})

	var msgs []int32
	msgs = append(msgs, playerId)
	msgs = append(msgs, playerInfo.Gold)

	skeleton.AsynCall(db.ChanRPC, "UpdateGolden", msgs, func(ret interface{}, err error) {
		log.Debug("===============ret", ret)
	})

	MsgChangeBirdS2C := &msg.MsgChangeBirdS2C{
		PlayerId: playerId,
		BirdId:   birdId,
	}

	userConn.WriteMsg(MsgChangeBirdS2C)

}

/**
 *
 * 修改名字
 * @param args
 * @return
 */
func handleChangeName(args []interface{}) {
	log.Debug("===============handleChangeName")
	message := args[0].(*msg.MsgChangeName)
	userConn := args[1].(gate.Agent)

	playerId := message.GetPlayerId()
	name := message.GetName()

	playerInfo := base.Get("user", playerId).(base.PlayerInfo)
	goldenNeed := playerInfo.NameNum * int32(nameBase)

	Success := 1
	if playerInfo.Gold < goldenNeed {
		Success = 0
		MsgChangeBirdS2C := &msg.MsgChangeNameS2C{
			Success: int32(Success),
		}
		userConn.WriteMsg(MsgChangeBirdS2C)
		return
	}
	playerInfo.NameNum = playerInfo.NameNum + 1
	playerInfo.Gold = playerInfo.Gold - goldenNeed
	playerInfo.NickName = name
	base.Put("user", playerId, playerInfo)
	log.Debug("===============UpdateName", playerInfo.NameNum)
	skeleton.AsynCall(db.ChanRPC, "UpdateName", args[0], func(ret interface{}, err error) {
		log.Debug("===============ret", ret)
	})

	var msgs []int32
	msgs = append(msgs, playerId)
	msgs = append(msgs, playerInfo.Gold)

	skeleton.AsynCall(db.ChanRPC, "UpdateGolden", msgs, func(ret interface{}, err error) {
		log.Debug("===============ret", ret)
	})

	MsgChangeBirdS2C := &msg.MsgChangeNameS2C{
		Success: int32(Success),
	}
	userConn.WriteMsg(MsgChangeBirdS2C)
}

/**
 *
 * 获取排名
 * @param args
 * @return
 */
func handleOnRank(args []interface{}) {
	//message := args[0].(*msg.MsgOnRank)
	userConn := args[1].(gate.Agent)

	var send *msg.MsgOnRankS2C
	defer func() {

	}()
	log.Debug("----------------------handleOnRank")
	skeleton.AsynCall(db.ChanRPC, "RankGolden", args[0], func(ret interface{}, err error) {
		if err != nil {
			log.Debug("BattleResult: err = ", err)
		} else {
			log.Debug("ret", ret)
			uinList := ret.([]int32)
			var players []*msg.PlayerInfo
			for _, uin := range uinList {
				info := base.Get("user", uin).(base.PlayerInfo)
				playerInfo := msg.PlayerInfo{
					PlayerId: info.PlayerId,
					NickName: info.NickName,
					IconUrl:  info.IconUrl,
					Gold:     info.Gold,
					Score:    info.Score,
					ItemId:   info.ItemId,
					BirdId:   info.BirdID,
					BirdNum:  info.BirdNum,
					NameNum:  info.NameNum,
				}
				players = append(players, &playerInfo)
			}
			log.Debug("players", players)
			send = &msg.MsgOnRankS2C{
				PlayerInfo: players,
			}
			log.Debug("send", send)
			userConn.WriteMsg(send)
		}
	})
}

/**
 *
 * 获取好友排名
 * @param args
 * @return
 */
func handleOnFriendIngo(args []interface{}) {
	//message := args[0].(*msg.MsgUseItem)
	//userConn := args[1].(gate.Agent)

}

/**
 *
 * 道具使用結果
 * @param args
 * @return
 */
func handleUseItemResult(args []interface{}) {

	message := args[0].(*msg.MsgUseItemResult)
	log.Debug("收到道具结果通知", message)
	roomId := message.GetRoomId();
	playerId := message.GetPlayerId()
	result := message.GetResult()
	value1 := message.GetValue1()
	value2 := message.GetValue2()

	roomInfo := base.Get("room", roomId).(base.Pk)
	send := msg.MsgUseItemResultS2C{
		RoomId:   roomId,
		PlayerId: playerId,
		Result:   result,
		Value1:   value1,
		Value2:   value2,
	}

	userItemAction(&roomInfo, send)

}
//道具效果
func userItemAction(roomInfo *base.Pk,send msg.MsgUseItemResultS2C)  {
	for _, v := range roomInfo.Players {
		if v == nil {
			continue
		}
		if v.PlayerId <= 0 {
			continue
		}
		if base.InitConn[v.PlayerId] != nil {
			log.Info("通知道具使用結果", v.PlayerId, base.InitConn[v.PlayerId])
			base.InitConn[v.PlayerId].WriteMsg(send)
		}
	}

	if send.Result == 1 {
		log.Debug("答题成功")
		return
	}
	log.Debug("答题失败爆炸")
	BoomAction(roomInfo, time.Now().Unix())
}

/// 爆炸
func BoomAction(roomInfo *base.Pk, t int64) {
	log.Debug(" 修改时间--start", time.Unix(t, 0))
	roomInfo.StartGameTime = t
	//todo 房间状态转换为结束状态
	roomInfo.Status = int32(msg.RoomState_END)
	base.Put("room", roomInfo.RoomNo, roomInfo)

	var players []*msg.PlayerInfo
	robotNum := 0
	for _, v := range roomInfo.Players {

		if nil == v {
			log.Debug("没有人  robotNum +1")
			robotNum += 1
			tempPlay := newPlayerInfoMsg(v)
			players = append(players, &tempPlay)
			continue
		} else if v.PlayerId <= 0 {
			log.Debug("playerID 《 0  robotNum +1")
			robotNum += 1
			tempPlay := newPlayerInfoMsg(v)
			players = append(players, &tempPlay)
			continue
		}
		userInfo := base.Get("user", v.PlayerId).(base.PlayerInfo)
		log.Debug("EggOwnerId is ",roomInfo.EggOwnerId)

		if userInfo.PlayerId == roomInfo.EggOwnerId {
			switch roomInfo.RewardType {
			case 1: //奖励金币
				userInfo.Gold += roomInfo.Value
			case 2: //扣除金币
				userInfo.Gold -= roomInfo.Value
			case 3: //奖励积分
				userInfo.Score += roomInfo.Value
			case 4: //扣除积分
				userInfo.Score -= roomInfo.Value
			case 5: //奖励道具
				userInfo.ItemId = append(v.ItemId, roomInfo.Value)
			}
		} else {
			//其他玩家增加金币
			userInfo.Gold += 100
			log.Debug("其他玩家增加金币 is ",userInfo)
		}
		base.Put("user",userInfo.PlayerId,userInfo)
		if userInfo.Online == false {
			log.Debug(" 托管 robotNum +1",userInfo)
			robotNum += 1
		}

		tempPlay := newPlayerInfoMsg(&userInfo)
		players = append(players, &tempPlay)
	}


	//todo 通知玩家信息
	MsgEnterRoomS2C := &msg.MsgEnterRoomS2C{
		RoomId:    roomInfo.RoomNo,
		RoomRound: roomInfo.RoundId,
		WaitTime:  3,
		Players:   players,
	}

	//todo 通知房间信息变化
	MsgRoomStateS2C := &msg.MsgRoomStateS2C{
		RoomState: int32(msg.RoomState_END),
		Time:      15,
		EggOwner:  0,
	}

	// todo 随机出itemid
	itemID := 0
	random := getRandom(*roomInfo)
	playerId := players[random].PlayerId

	randomRate := rand.Intn(9)
	if randomRate < 3 {
		log.Debug("恭喜获得道具")
		itemID = rand.Intn(1) + 1
		playerInfo := base.Get("user", playerId).(base.PlayerInfo)
		playerInfo.ItemId = append(playerInfo.ItemId, int32(itemID))
		base.Put("user",playerInfo.PlayerId,playerInfo)
	}

	// todo  通知所有人蛋暴炸
	MsgEggBoomS2C := &msg.MsgEggBoomS2C{
		RoomId:     roomInfo.RoomNo,
		BoomId:     roomInfo.EggOwnerId,
		RewardType: roomInfo.RewardType,
		Value:      roomInfo.Value,
		PlayerId:   playerId,
		ItemID:     int32(itemID),
	}

	for _, v := range roomInfo.Players {
		if v == nil {
			continue
		}
		if v.PlayerId <= 0 {
			continue
		}
		if nil != base.InitConn[v.PlayerId] {
			base.InitConn[v.PlayerId].WriteMsg(MsgEggBoomS2C)
			base.InitConn[v.PlayerId].WriteMsg(MsgEnterRoomS2C)
			base.InitConn[v.PlayerId].WriteMsg(MsgRoomStateS2C)
		}
	}
	if robotNum == int(len(roomInfo.Players)) {
		//所有人都挂機，結束
		log.Debug("删除房间", roomInfo.RoomNo,robotNum, len(roomInfo.Players))
		roomInfo.Destroy = true
		base.Put("room", roomInfo.RoomNo, roomInfo)
	}
}

//传蛋动作
func ChangeEggOwner(playersID []int32, room *base.Pk, userId int32, needSelf bool) {
	if len(playersID) > 0 {

		length := len(playersID)
		targerNum := rand.Intn(length)
		targerId := playersID[targerNum]

		////////////////////////////////////////////////////////////////////////
		log.Debug("----------------------------------------------------")
		fmt.Println("房间人数", len(playersID))
		fmt.Println("targerNum", targerNum)
		log.Debug("roomInfo.EggOwnerId is ：========,", room.EggOwnerId)
		log.Debug("targerId is ：========,", targerId)
		log.Debug("----------------------------------------------------")
		////////////////////////////////////////////////////////////////////////

		room.GetEggTime = time.Now().Unix()
		base.Put("room", room.RoomNo, room)
		MsgChangeEggS2C := &msg.MsgChangeEggS2C{
			RoomId:   room.RoomNo,
			PlayerId: room.EggOwnerId,
			TargerId: targerId,
		}
		room.EggOwnerId = targerId
		base.Put("room", room.RoomNo, room)
		for _, v := range room.Players {
			if nil == v {
				continue
			}
			if nil != base.InitConn[v.PlayerId] {
				if needSelf == false{
					if userId == v.PlayerId{
						continue
					}
				}
				base.InitConn[v.PlayerId].WriteMsg(MsgChangeEggS2C)
			}
		}

		// todo 判断目标身上是否有道具状态
		targerInfo := base.Get("user",targerId).(base.PlayerInfo)
		if targerInfo.UsedItem == 0{
			log.Debug("目标身上没有道具",targerId)
			return
		}
		itemKey := targerInfo.UsedItem

		itemInfoInter := base.Get("item",itemKey)
		if itemInfoInter == nil {
			log.Error("物品不存在",itemKey)
			return
		}
		itemInfo := itemInfoInter.(base.ItemInfo)
		UsedItem := itemInfo.ItemID
		targerInfo.UsedItem = 0
		base.Put("user", targerId,targerInfo)

		log.Debug("目标身上有道具,触发道具效果",targerId)
		// todo 爆炸时间延迟
		room.BoomTime += conf.Server.AnswerTime

		// todo 状态下托管不自动传蛋
		room.Status = int32(msg.RoomState_Answer)

		// todo 记录答题时间
		room.AnswerTime = time.Now().Unix()
		// 存库
		base.Put("room",room.RoomNo,room)

		//todo 通知所有玩家 道具触发

		MsgUseActionS2C := msg.MsgUseActionS2C{
			RoomId:room.RoomNo,
			PlayerId:targerId,
			ItemId:UsedItem,
		}
		for _, roomPlayer := range room.Players{
			if roomPlayer == nil{
				continue
			}
			if roomPlayer.PlayerId <= 0{
				continue
			}
			if base.InitConn[roomPlayer.PlayerId] != nil {
				pushInfo := base.Get("user", roomPlayer.PlayerId).(base.PlayerInfo)
				if pushInfo.RoomNo != room.RoomNo {
					continue
				}
				log.Debug(roomPlayer.PlayerId, "通知所有人道具触发 MsgUseActionS2C", MsgUseActionS2C)
				base.InitConn[roomPlayer.PlayerId].WriteMsg(MsgUseActionS2C)
			}
		}
		base.Delete("item",itemKey)
	}
}



func GiveBackItem(itemKey int32)  {
	ItemInfoInt := base.Get("item",itemKey)
	if nil == ItemInfoInt{
		return
	}
	itemInfo :=ItemInfoInt.(base.ItemInfo)
	playerId := itemInfo.UserID
	status := itemInfo.Status
	itemId := itemInfo.ItemID

	if status == 1{
		return
	}
	playerInfo := base.Get("user",playerId).(base.PlayerInfo)
	playerInfo.ItemId = append(playerInfo.ItemId, itemId)
	base.Put("user",playerId,playerInfo)

}